import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { customerApi } from '../api/module/CustomerApi.ts'
import { type User } from '../types/DataTypes'
export const useAuthStore = defineStore('auth', () => {
  // 状态
  const isLoggedIn = ref(false)
  const user = ref<User | null>(null)
  const loading = ref(false)

  // getters
  const getCustomerId = computed(() => user.value?.customerId || '')
  const getCustomerName = computed(() => user.value?.customerName || '')
  const isRememberMe = computed(() => user.value?.rememberMe || false)

  // actions
  const login = async (customerName: string, customerId: string, rememberMe: boolean = false) => {
    loading.value = true

    try {
      // 1. 首先检查用户名是否存在
      const nameCheckResponse = await customerApi.checkCustomerNameExists(customerName)
      if (nameCheckResponse.success && (nameCheckResponse.data as any).exists) {
        // 2. 用户名存在，进行登录验证
        const verifyResponse = await customerApi.verifyLogin(customerName, customerId)

        if (verifyResponse.success) {
          // 登录成功
          isLoggedIn.value = true
          user.value = { customerId, customerName, rememberMe }

          // 保存到localStorage
          if (rememberMe) {
            localStorage.setItem('auth_customerId', customerId)
            localStorage.setItem('auth_customerName', customerName)
            localStorage.setItem('rememberMe', 'true')
          } else {
            localStorage.removeItem('auth_customerId')
            localStorage.removeItem('auth_customerName')
            localStorage.removeItem('rememberMe')
          }
          localStorage.setItem('auth_isLoggedIn', 'true')

          ElMessage.success('登录成功')
          return { success: true }
        } else {
          // 验证失败
          return { success: false, error: verifyResponse.message || '用户ID不正确' }
        }
      } else {
        // 3. 用户名不存在，提示用户注册
        const confirmRegister = await ElMessageBox.confirm(
            `用户名 "${customerName}" 不存在，是否立即注册？`,
            '用户不存在',
            {
              confirmButtonText: '注册',
              cancelButtonText: '取消',
              type: 'warning'
            }
        )

        if (confirmRegister) {
          // 用户同意注册
          return await register(customerName, customerId, rememberMe)
        } else {
          // 用户取消注册
          return { success: false, error: '已取消注册' }
        }
      }
    } catch (error: any) {
      // console.error('Login error:', error)

      // 处理用户取消确认框的情况
      if (error === 'cancel' || error === 'close') {
        return { success: false, error: '已取消注册' }
      }

      return { success: false, error: '登录失败，请稍后重试' }
    } finally {
      loading.value = false
    }
  }

  // 注册并登录
  const register = async (customerName: string, customerId: string, rememberMe: boolean) => {
    try {
      // 注册新用户
      const registerResponse = await customerApi.addCustomer({
        customerName,
        customerId
      })

      if (registerResponse.success) {
        ElMessage.success('注册成功, 请重新登录')
        return { success: true, message: '新用户已注册' }
      } else {
        return { success: false, error: registerResponse.message || '注册失败' }
      }
    } catch (error) {
      console.error('Register error:', error)
      return { success: false, error: '注册失败，请稍后重试' }
    }
  }

  const logout = () => {
    isLoggedIn.value = false
    user.value = null
    localStorage.removeItem('auth_isLoggedIn')
    if(localStorage.getItem('rememberMe')===null){
      localStorage.removeItem('auth_customerId')
      localStorage.removeItem('auth_customerName')
    }
    ElMessage.success('已退出登录')
  }

  const checkAuth = () => {
    const savedIsLoggedIn = localStorage.getItem('auth_isLoggedIn') === 'true'
    const savedRememberMe = localStorage.getItem('rememberMe') === 'true'
    const savedCustomerId = localStorage.getItem('auth_customerId')
    const savedCustomerName = localStorage.getItem('auth_customerName')

    if (savedIsLoggedIn && savedCustomerId && savedCustomerName) {
      isLoggedIn.value = true
      user.value = {
        customerId: savedCustomerId,
        customerName: savedCustomerName,
        rememberMe: savedRememberMe
      }
    }
  }

  // 初始化时检查认证状态
  checkAuth()

  return {
    // state
    isLoggedIn,
    user,
    loading,

    // getters
    getCustomerId,
    getCustomerName,
    isRememberMe,

    // actions
    login,
    logout,
    checkAuth
  }
})